<script setup>
import orderAPI from '../api/order_api.js'
import productAPI from '../api/product_api.js'
import buycarAPI from '../api/buycar_api.js'
import categoryAPI from '../api/category_api.js'
import brandAPI from '../api/brand_api.js'

import { ref, onMounted, inject, reactive } from "vue";
import {
  ElMessageBox,
  ElPagination,
  ElTable,
  ElTableColumn,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElButton,
  ElPopover,
  ElTag,
  ElIcon,
  ElSelect,
  ElOption,
  ElInputNumber
} from 'element-plus';
import { Timer, ShoppingCart } from '@element-plus/icons-vue';
import lodash from 'lodash';

// 从全局获取登录用户信息
const loginAdmin = inject('loginAdmin');

// 表格数据 & 分页数据
const tableData = ref([]);
const total = ref(0);

// 查询条件
const searchObj = ref({
  current: 1,
  limit: 10,
  name: '',
  category_id: '',
  brand_id: ''
});

// 商品数据
const products = ref([]);
// 分类和品牌下拉数据
const categories = ref([]);
const brands = ref([]);

// 购买弹窗相关
const buyWinVisible = ref(false);
const buyForm = ref({
  product_id: '',
  product_name: '',
  receiver: '',
  shipping_address: '',
  receiver_phone: '',
  nums: 1,
  price: 0
});

// 表单引用和验证规则
const buyFormRef = ref(null);
const buyRules = reactive({
  nums: [
    { required: true, message: '请输入购买数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '购买数量不能小于1', trigger: 'blur' }
  ],
  receiver: [
    { required: true, message: '请输入收件人', trigger: 'blur' }
  ],
  shipping_address: [
    { required: true, message: '请输入收货地址', trigger: 'blur' }
  ],
  receiver_phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' }
  ]
});

// 页面加载时初始化数据
onMounted(async () => {
  await loadProducts();
  await loadCategories();
  await loadBrands();
});

// 加载商品列表
const loadProducts = async () => {
  try {
    const result = await productAPI.page(searchObj.value);
    products.value = result.data || [];
    total.value = result.count || 0;
  } catch (error) {
    console.error('查询商品失败:', error);
    ElMessageBox.alert('查询商品失败，请稍后重试', '错误', { type: 'error' });
  }
};

// 加载分类下拉列表
const loadCategories = async () => {
  try {
    const result = await categoryAPI.page({ current: 1, limit: 100 });
    categories.value = result.data || [];
  } catch (error) {
    console.error('加载分类失败:', error);
    ElMessageBox.alert('加载分类失败，请稍后重试', '错误', { type: 'error' });
  }
};

// 加载品牌下拉列表
const loadBrands = async () => {
  try {
    const result = await brandAPI.page({ current: 1, limit: 100 });
    brands.value = result.data || [];
  } catch (error) {
    console.error('加载品牌失败:', error);
    ElMessageBox.alert('加载品牌失败，请稍后重试', '错误', { type: 'error' });
  }
};

// 根据ID获取分类名称
const getCategoryName = (id) => {
  if (!id) return '未选择';
  const category = categories.value.find(item => item.id === id);
  return category ? category.name : '未知分类';
};

// 根据ID获取品牌名称
const getBrandName = (id) => {
  if (!id) return '未选择';
  const brand = brands.value.find(item => item.id === id);
  return brand ? brand.name : '未知品牌';
};

// 分页改变事件
const handleSizeChange = () => {
  loadProducts();
};
const handleCurrentChange = () => {
  loadProducts();
};

// 搜索按钮点击事件
const handlerSearch = async () => {
  searchObj.value.current = 1;
  await loadProducts();
};

// 打开购买弹窗
const handleBuy = (product) => {
  buyForm.value = {
    product_id: product.id,
    product_name: product.name,
    receiver: loginAdmin.value.name || '',
    shipping_address: '',
    receiver_phone: loginAdmin.value.phone || '',
    nums: 1,
    price: product.price
  };
  buyWinVisible.value = true;
};

// 取消购买
const buyCancel = () => {
  buyWinVisible.value = false;
};

// 提交订单
const submitOrder = async () => {
  // 先进行表单验证
  await buyFormRef.value.validate();

  try {
    // 1. 检查库存是否充足
    const product = await productAPI.get(buyForm.value.product_id);
    if (product.nums < buyForm.value.nums) {
      return ElMessageBox.alert('库存不足', '提示', { type: 'warning' });
    }

    // 2. 构建订单对象并提交
    const order = {
      product_id: buyForm.value.product_id,
      user_id: loginAdmin.value.id,
      receiver: buyForm.value.receiver,
      shipping_address: buyForm.value.shipping_address,
      receiver_phone: buyForm.value.receiver_phone,
      nums: buyForm.value.nums,
      total_amount: buyForm.value.nums * buyForm.value.price,
      order_status: 0
    };

    await orderAPI.add(order);

    // 3. 订单提交成功后，更新商品库存
    const updatedProduct = {
      ...product,
      nums: product.nums - buyForm.value.nums
    };
    await productAPI.edit(updatedProduct);

    ElMessageBox.alert('订单提交成功，库存已更新', '成功', { type: 'success' });
    buyWinVisible.value = false;
    // 4. 重新加载商品列表以显示更新后的库存
    await loadProducts();
  } catch (error) {
    // 验证失败不执行后续操作
    if (error.name !== 'Error') {
      console.error('提交订单失败:', error);
      ElMessageBox.alert('提交订单失败，请稍后重试', '错误', { type: 'error' });
    }
  }
};

// 加入购物车
const addToCart = async (product) => {
  try {
    // 检查是否已登录
    if (!loginAdmin.value.id) {
      return ElMessageBox.alert('请先登录', '提示', { type: 'warning' });
    }

    // 检查购物车中是否已有该商品
    const cartResult = await buycarAPI.page({
      user_id: loginAdmin.value.id,
      product_id: product.id,
      current: 1,
      limit: 1
    });

    if (cartResult.data && cartResult.data.length > 0) {
      // 商品已在购物车中，更新数量
      const cartItem = cartResult.data[0];
      await buycarAPI.edit({
        id: cartItem.id,
        user_id: loginAdmin.value.id,
        product_id: product.id,
        nums: cartItem.nums + 1
      });
      ElMessageBox.alert('商品已添加到购物车，数量+1', '成功', { type: 'success' });
    } else {
      // 新增商品到购物车
      await buycarAPI.add({
        user_id: loginAdmin.value.id,
        product_id: product.id,
        nums: 1
      });
      ElMessageBox.alert('商品已添加到购物车', '成功', { type: 'success' });
    }
  } catch (error) {
    console.error('加入购物车失败:', error);
    ElMessageBox.alert('加入购物车失败，请稍后重试', '错误', { type: 'error' });
  }
};
</script>

<template>
  <!-- 搜索表单 -->
  <el-form :inline="true" :model="searchObj" class="demo-form-inline" style="margin-top:10px ">
    <el-form-item label="商品名称">
      <el-input v-model="searchObj.name" placeholder="请输入商品名称" clearable />
    </el-form-item>

    <el-form-item label="分类">
      <el-select
          v-model="searchObj.category_id"
          placeholder="请选择分类"
          clearable
          style="width: 200px"
      >
        <el-option
            v-for="item in categories"
            :key="item.id"
            :label="item.name"
            :value="item.id"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="品牌">
      <el-select
          v-model="searchObj.brand_id"
          placeholder="请选择品牌"
          clearable
          style="width: 200px"
      >
        <el-option
            v-for="item in brands"
            :key="item.id"
            :label="item.name"
            :value="item.id"
        />
      </el-select>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="handlerSearch">查询</el-button>
    </el-form-item>
  </el-form>

  <!-- 商品表格 -->
  <el-table :data="products" style="width: 100%" border>
    <el-table-column label="ID" width="80" align="center">
      <template #default="scope">
        <el-tag>{{ scope.row.id }}</el-tag>
      </template>
    </el-table-column>

    <el-table-column label="商品名称" width="180" align="center">
      <template #default="scope">
        <el-tag>{{ scope.row.name }}</el-tag>
      </template>
    </el-table-column>

    <el-table-column label="分类" width="100" align="center">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>分类 ID: {{ scope.row.category_id }}</div>
          </template>
          <template #reference>
            <el-tag>{{ getCategoryName(scope.row.category_id) }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>

    <el-table-column label="品牌" width="100" align="center">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>品牌 ID: {{ scope.row.brand_id }}</div>
          </template>
          <template #reference>
            <el-tag>{{ getBrandName(scope.row.brand_id) }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>

    <el-table-column label="型号" width="180" align="center">
      <template #default="scope">
        <el-tag>{{ scope.row.model }}</el-tag>
      </template>
    </el-table-column>

    <el-table-column label="价格" width="100" align="center">
      <template #default="scope">
        <el-tag>{{ scope.row.price }}</el-tag>
      </template>
    </el-table-column>

    <el-table-column label="商品图片" width="120" align="center">
      <template #default="scope">
        <div class="img-preview">
          <img
              :src="scope.row.img || 'https://xrysitu.oss-cn-beijing.aliyuncs.com/a2b619ac-9909-4af9-b75b-5e0fee3b7473.jpg'"
              alt="商品图片"
              class="product-img"
              @error="(e) => e.target.src = 'https://xrysitu.oss-cn-beijing.aliyuncs.com/a2b619ac-9909-4af9-b75b-5e0fee3b7473.jpg'"
          />
        </div>
      </template>
    </el-table-column>

    <el-table-column label="库存数" width="100" align="center">
      <template #default="scope">
        <div style="display: flex; align-items: center; justify-content: center">
          <el-icon><Timer /></el-icon>
          <span style="margin-left: 10px">{{ scope.row.nums }}</span>
        </div>
      </template>
    </el-table-column>

    <el-table-column label="操作" align="center">
      <template #default="scope">
        <el-button size="small" type="primary" @click="handleBuy(scope.row)">
          购买
        </el-button>
        <el-button
            size="small"
            type="success"
            @click="addToCart(scope.row)"
        >
          <el-icon><ShoppingCart /></el-icon>
          加入购物车
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页组件 -->
  <el-pagination
      v-model:current-page="searchObj.current"
      v-model:page-size="searchObj.limit"
      :page-sizes="[10, 20, 30, 50]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 10px; text-align: right;"
  />

  <!-- 购买弹窗 -->
  <el-dialog v-model="buyWinVisible" title="购买商品" width="500">
    <el-form
        :model="buyForm"
        label-width="120px"
        :rules="buyRules"
        ref="buyFormRef"
    >
      <el-form-item label="商品名称">
        <el-input v-model="buyForm.product_name" disabled />
      </el-form-item>

      <el-form-item label="单价">
        <el-input v-model="buyForm.price" disabled />
      </el-form-item>

      <el-form-item label="购买数量" prop="nums">
        <el-input-number
            v-model="buyForm.nums"
            :min="1"
            :step="1"
            label="购买数量"
        />
      </el-form-item>

      <el-form-item label="收件人" prop="receiver">
        <el-input v-model="buyForm.receiver" placeholder="请输入收件人" />
      </el-form-item>

      <el-form-item label="收货地址" prop="shipping_address">
        <el-input v-model="buyForm.shipping_address" type="textarea" rows="3" placeholder="请输入收货地址" />
      </el-form-item>

      <el-form-item label="联系电话" prop="receiver_phone">
        <el-input v-model="buyForm.receiver_phone" placeholder="请输入联系电话" />
      </el-form-item>

      <el-form-item label="合计金额">
        <el-input :value="buyForm.nums * buyForm.price" disabled />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="buyCancel">取消</el-button>
        <el-button type="primary" @click="submitOrder">
          提交订单
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.el-table {
  margin-top: 10px;
}

.img-preview {
  width: 80px;
  height: 80px;
  margin: 0 auto;
  overflow: hidden;
  border-radius: 4px;
  border: 1px solid #eee;
}

.product-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.product-img:hover {
  transform: scale(1.1);
}

.el-form-item {
  margin-bottom: 15px;
}
</style>